package com.psnail.master.service.Impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.psnail.master.entity.Answer;
import com.psnail.master.entity.AnswerExample;
import com.psnail.master.entity.Demand;
import com.psnail.master.entity.FocusD;
import com.psnail.master.entity.FocusDExample;
import com.psnail.master.entity.FocusDExample.Criteria;
import com.psnail.master.entity.User;
import com.psnail.master.mapper.AnswerMapper;
import com.psnail.master.mapper.DemandMapper;
import com.psnail.master.mapper.FocusDMapper;
import com.psnail.master.mapper.UserMapper;
import com.psnail.master.service.DemandService;
import com.psnail.tools.Data2Html;
import com.psnail.tools.EmailTools;
import com.psnail.tools.IDTools;

@Service
public class DemandServiceImpl implements DemandService {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private EmailTools ets;
	@Autowired
	HttpServletRequest request;
	@Autowired
	FocusDMapper focusDMapper;
	@Autowired
	AnswerMapper answerMapper;
	@Autowired
	DemandMapper demandMapper;
	@Autowired
	private UserMapper userMapper;

	// 咨询问题解答的地址
	@Value("${email.demand.answer}")
	private String demandAnswer;
	// 站长邮箱
	@Value("${email.code.zhanzhang}")
	private String zhanzhang;
	// 管理员邮箱
	@Value("${email.code.guanliyuan}")
	private String guanliyuan;

	@Override
	public Map<String, Object> guanzhu(String id) {
		Map<String, Object> result = new HashMap<String, Object>();
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute("user");
		if (user == null) {
			result.put("status", 0);
			result.put("message", "尚未登录！");
		} else {
			FocusDExample example = new FocusDExample();
			Criteria criteria = example.createCriteria();
			criteria.andUserIdEqualTo(user.getId());
			criteria.andDemandIdEqualTo(id);
			int row = focusDMapper.countByExample(example);
			if (row > 0) {
				result.put("status", 0);
				result.put("message", "您已经关注过了！");
			} else {
				FocusD fd = new FocusD();
				fd.setUserId(user.getId());
				fd.setUserEmail(user.getEmail());
				fd.setDemandId(id);
				fd.setTime(new Date());
				row = focusDMapper.insert(fd);
				if (row > 0) {
					result.put("status", 1);
					result.put("message", "已关注！");
				} else {
					result.put("status", 0);
					result.put("message", "关注失败！请联系站长。");
				}
			}
		}
		return result;
	}

	@Override
	@Transactional
	public Map<String, Object> answer(String id, String content) {
		Map<String, Object> result = new HashMap<String, Object>();
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute("user");
		if (id == null || "".equals(id)) {
			result.put("status", 0);
			result.put("message", "没有此需求资源！");
		} else if (content == null || "".equals(content)) {
			result.put("status", 0);
			result.put("message", "请输入解决方案！");
		} else if (user == null) {
			result.put("status", 0);
			result.put("message", "尚未登录！");
		} else {
			Answer answer = new Answer();
			String a_id = IDTools.createId();
			answer.setId(a_id);
			answer.setContent(content);
			answer.setState(1);
			answer.setDemandId(id);
			answer.setUserId(user.getId());
			answer.setTime(new Date());
			int row = answerMapper.insert(answer);
			if (row > 0) {
				Demand d = demandMapper.selectByPrimaryKey(id);
				d.setState(2);
				row = demandMapper.updateByPrimaryKey(d);
				if (row > 0) {
					String subject = "[蜗牛库]一条新的解决方案";
					String c = "详情：<br/>您在蜗牛库站上提出的需求：《" + d.getTitle() + "》有了一条新的解决方案，点击下方链接查看详情。<br/>" + demandAnswer
							+ "?id=" + a_id;
					try {
						ets.sendEmail(userMapper.selectByPrimaryKey(d.getUserId()).getEmail(), subject, c);
					} catch (Exception e) {
						logger.error("ResourceServiceImpl/answer()发送邮件出现异常");
						result.put("status", 0);
						result.put("message", "您的解决方案通过邮件发送给需求用户过程中出现异常！请保留截图联系站长。");
					}
					result.put("status", 1);
					result.put("message", "您的解决方案已经通过邮件成功发送给需求用户！非常感谢您的热心解答。");
				} else {
					result.put("status", 0);
					result.put("message", "更改需求状态失败！请联系站长。");
				}
			} else {
				result.put("status", 0);
				result.put("message", "发布解决方案失败！请联系站长。");
			}
		}
		return result;
	}

	@Override
	public String detail2Html(String id) {
		Demand demand = new Demand();
		demand = demandMapper.selectByPrimaryKey(id);
		AnswerExample example = new AnswerExample();
		com.psnail.master.entity.AnswerExample.Criteria criteria = example.createCriteria();
		criteria.andDemandIdEqualTo(id);
		List<Answer> answers = answerMapper.selectByExample(example);
		return Data2Html.demandDetailToHtml(demand, answers);
	}

	@Override
	public Map<String, Object> getAnswerAndDemand(String id) {
		Map<String, Object> result = new HashMap<String, Object>();
		Answer answer = new Answer();
		answer = answerMapper.selectByPrimaryKey(id);
		if (answer == null) {
			result.put("status", 0);
			result.put("message", "此解决方案已不存在！请联系站长。");
		} else {
			Demand demand = new Demand();
			demand = demandMapper.selectByPrimaryKey(answer.getDemandId());
			if (demand == null) {
				result.put("status", 0);
				result.put("message", "此需求已不存在！请联系站长。");
			} else {
				result.put("status", 1);
				result.put("message", "查询成功。");
				result.put("title", demand.getTitle());
				result.put("content", answer.getContent());
			}
		}

		return result;
	}

	@Override
	public Map<String, Object> validateAnswer(String id, String state) {
		Map<String, Object> result = new HashMap<String, Object>();
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute("user");
		if (user == null) {
			result.put("status", 0);
			result.put("message", "尚未登录！");
		} else {
			Answer answer = new Answer();
			answer = answerMapper.selectByPrimaryKey(id);
			if (answer == null) {
				result.put("status", 0);
				result.put("message", "此解决方案已不存在！请联系站长");
			} else if (answer.getState() > 1) {
				result.put("status", 0);
				result.put("message", "此解决方案已经验证过了！");
			} else {
				Demand demand = new Demand();
				demand = demandMapper.selectByPrimaryKey(answer.getDemandId());
				if (demand == null) {
					result.put("status", 0);
					result.put("message", "此需求已不存在！请联系站长");
				} else if (!user.getId().equals(demand.getUserId()) && !zhanzhang.contains(user.getEmail())
						&& !guanliyuan.contains(user.getEmail())) {
					result.put("status", 0);
					result.put("message", "你没有权限进行验证！");
				} else {
					answer.setState(Integer.valueOf(state));
					int row = answerMapper.updateByPrimaryKey(answer);
					if (row > 0) {
						if (demand.getState() != 3 && "3".equals(state)) {
							demand.setState(3);
							demandMapper.updateByPrimaryKey(demand);
						}
						result.put("status", 1);
						result.put("message", "提交成功！感谢您的支持。");
						result.put("demand_id", demand.getId());
					} else {
						result.put("status", 0);
						result.put("message", "提交失败！请联系站长。");
					}
				}

			}
		}
		return result;
	}

}